# SqlsugarService.API 自动启动脚本
param(
    [int]$Port = 8080,
    [string]$Environment = "Development",
    [switch]$OpenBrowser = $true
)

Write-Host "=== SqlsugarService.API 启动脚本 ===" -ForegroundColor Green

# 检查发布目录
$publishPath = "bin\Release\net6.0\publish"
if (-not (Test-Path $publishPath)) {
    Write-Host "❌ 发布目录不存在: $publishPath" -ForegroundColor Red
    Write-Host "请先运行: dotnet publish --configuration Release" -ForegroundColor Yellow
    exit 1
}

# 检查端口是否可用
Write-Host "检查端口 $Port 是否可用..." -ForegroundColor Yellow
$portTest = Test-NetConnection -ComputerName "localhost" -Port $Port -WarningAction SilentlyContinue
if ($portTest.TcpTestSucceeded) {
    Write-Host "⚠️ 端口 $Port 已被占用，尝试查找可用端口..." -ForegroundColor Yellow
    
    # 尝试其他端口
    $alternatePorts = @(8080, 9000, 9001, 9002, 8081, 8082)
    $foundPort = $null
    
    foreach ($testPort in $alternatePorts) {
        $test = Test-NetConnection -ComputerName "localhost" -Port $testPort -WarningAction SilentlyContinue
        if (-not $test.TcpTestSucceeded) {
            $foundPort = $testPort
            break
        }
    }
    
    if ($foundPort) {
        $Port = $foundPort
        Write-Host "✅ 找到可用端口: $Port" -ForegroundColor Green
    } else {
        Write-Host "❌ 无法找到可用端口，请手动指定" -ForegroundColor Red
        exit 1
    }
} else {
    Write-Host "✅ 端口 $Port 可用" -ForegroundColor Green
}

# 设置环境变量
$env:ASPNETCORE_ENVIRONMENT = $Environment
$env:ASPNETCORE_URLS = "http://localhost:$Port"

Write-Host "环境设置:" -ForegroundColor Cyan
Write-Host "  环境: $Environment" -ForegroundColor Gray
Write-Host "  URL: http://localhost:$Port" -ForegroundColor Gray

# 进入发布目录
$originalLocation = Get-Location
try {
    Set-Location $publishPath
    Write-Host "当前目录: $(Get-Location)" -ForegroundColor Gray
    
    # 如果需要，打开浏览器
    if ($OpenBrowser) {
        Write-Host "正在打开浏览器..." -ForegroundColor Cyan
        Start-Sleep -Seconds 2  # 给应用一点启动时间
        Start-Process "http://localhost:$Port"
    }
    
    Write-Host "`n🚀 启动应用程序..." -ForegroundColor Green
    Write-Host "按 Ctrl+C 停止应用" -ForegroundColor Yellow
    Write-Host "访问地址: http://localhost:$Port" -ForegroundColor Cyan
    Write-Host "Swagger文档: http://localhost:$Port/swagger" -ForegroundColor Cyan
    Write-Host "健康检查: http://localhost:$Port/health" -ForegroundColor Cyan
    Write-Host ""
    
    # 启动应用
    dotnet SqlsugarService.API.dll
    
} catch {
    Write-Host "❌ 启动失败: $($_.Exception.Message)" -ForegroundColor Red
} finally {
    Set-Location $originalLocation
}

Write-Host "`n应用已停止" -ForegroundColor Yellow
